<?php 
header('Content-Type:text/html; charset=utf-8');
include_once dirname(__FILE__) . "/config.php";
$dir = dirname(__FILE__) . '/data/';
$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$sfile = array(
    array(
        'path' => $dir.'house_'.$date.'.php' , 
        'tablename' => 'house'
    ),
    array(
        'path' => $dir.'bank_'.$date.'.php' , 
        'tablename' => 'bank'
    ),
    array(
        'path' => $dir.'computer_'.$date.'.php' , 
        'tablename' => 'computer'
    ),
    array(
        'path' => $dir.'steel_'.$date.'.php' , 
        'tablename' => 'steel'
    ),
);

$mysqli = new mysqli($dbConf['host'], $dbConf['username'], $dbConf['passwd'], $dbConf['dbname']);
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
}
foreach ($sfile as $fv) {
    $sql = "select count(1) from {$fv['tablename']} where rdate = '$date'";
    if ($result = $mysqli->query($sql)) {
        print_r($result->fetch_row());
        $row = $result->fetch_row();
        if ($row[0] > 0) {
            echo '今日数据已经保存于数据表' . $fv['tablename'] . '，请勿重复保存！<br>' . "\n";
            exit();
        }
        $result->close();
    }
    if (file_exists($fv['path'])) {
        $json = include $fv['path'];
        $aData = json_decode($json);
        foreach ($aData as $k => $v) {
            array_pop($v);
            $cols = "'" . implode("','", $v) . "'";
            $sql = "insert into {$fv['tablename']} values(null,$cols,'$date')";
            if ($r = $mysqli->query($sql)) {
                //$r->close();
            }
        }
        echo '今日数据已经成功保存于数据表' . $fv['tablename'] . '<br>' . "\n";
    }
}
$mysqli->close();
?>